package com.xbn.xbnmall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xbn.common.constant.ProductConstant;
import com.xbn.xbnmall.product.dao.AttrAttrgroupRelationDao;
import com.xbn.xbnmall.product.dao.AttrGroupDao;
import com.xbn.xbnmall.product.dao.CategoryDao;
import com.xbn.xbnmall.product.entity.AttrAttrgroupRelationEntity;
import com.xbn.xbnmall.product.entity.AttrGroupEntity;
import com.xbn.xbnmall.product.entity.CategoryEntity;
import com.xbn.xbnmall.product.service.CategoryService;
import com.xbn.xbnmall.product.vo.AttrGroupRelationVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xbn.common.utils.PageUtils;
import com.xbn.common.utils.Query;

import com.xbn.xbnmall.product.dao.AttrDao;
import com.xbn.xbnmall.product.entity.AttrEntity;
import com.xbn.xbnmall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import com.xbn.xbnmall.product.vo.AttrRespVo;
import com.xbn.xbnmall.product.vo.AttrVo;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    private AttrGroupDao attrGroupDao;
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private CategoryService categoryService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        //先存储属性
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.save(attrEntity);
        //再存储属性和属性分组之间的关系，如果是销售属性  attr_type为0的就不用保存关联关系了
        if(attr.getAttrType()== ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()
        &&attr.getAttrGroupId()!=null) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }
    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        //基本属性是1，销售属性为0
        wrapper.eq("attr_type","base".equalsIgnoreCase(type)
                ?ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():
                ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if(catelogId!=0)
        {
            wrapper.eq("catelog_id",catelogId);
        }
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key))
        {
            wrapper.and((wrapper1)->{
            wrapper1.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        //得到分页内容中的数据纪录,查询结果中要有分类的名字和分组名字，这两个要额外查询
        //然后封装到AttrRespVo中
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> respVos = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            //1、设置分组名字(只有基本属性有分组)
            if("base".equalsIgnoreCase(type)) {
                AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_id", attrEntity.getAttrId()));
                //属性分组和属性的关系可能为空，可能该属性还没有录入分组
                if (relationEntity != null&&relationEntity.getAttrGroupId()!=null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            //2、设置分组名称
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(respVos);
        return pageUtils;
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        //先查出当前属性的详细信息
        AttrEntity attrEntity = this.getById(attrId);

        AttrRespVo attrRespVo=new AttrRespVo();
        BeanUtils.copyProperties(attrEntity,attrRespVo);
        //查询所属分组信息,销售属性没有分组信息
        if(attrEntity.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.
                    selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (relationEntity != null) {
                attrRespVo.setAttrGroupId(relationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if (attrGroupEntity != null) {
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }


        //设置分类信息
        Long catelogId = attrEntity.getCatelogId();
        attrRespVo.setCatelogPath(categoryService.findCatelogPath(catelogId));
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if(categoryEntity!=null)
        {
            attrRespVo.setCatelogName(categoryEntity.getName());
        }
        return attrRespVo;
    }
    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
    //基本数据修改，属性基本数据
        AttrEntity attrEntity = new AttrEntity();
    BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);
        //关联关系修改,修改这个属性是在哪个分组关系下的(基本属性要修改，销售属性不需要)
        if(attrEntity.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {

            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());

            UpdateWrapper<AttrAttrgroupRelationEntity> wrapper = new UpdateWrapper<AttrAttrgroupRelationEntity>().
                    eq("attr_id", attr.getAttrId());
            Integer count = attrAttrgroupRelationDao
                    .selectCount(wrapper);
            if (count != 0) {
                //数据库中已经有关联关系了就修改
                attrAttrgroupRelationDao.update(relationEntity, wrapper);
            } else {
                //数据库没有属性和属性分组关联关系就新增
                attrAttrgroupRelationDao.insert(relationEntity);
            }
        }

    }

    /*
    * 根据分组id查找关联的所有基本属性
    * */
    @Override
    public List<AttrEntity> getRelationAttr(Long attegroundId) {
        List<AttrAttrgroupRelationEntity> relations = attrAttrgroupRelationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_group_id", attegroundId)
        );
        //收集所有该attegroundId 对应的组下的属性id
        List<Long> attrIds = relations.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        if(attrIds==null||attrIds.size()==0)
        {
            return null;
        }
        Collection<AttrEntity> attrEntities = this.listByIds(attrIds);
        return (List<AttrEntity>) attrEntities;
    }




    /*
    * 删除关联关系
    * */
    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
        List<AttrAttrgroupRelationEntity> entities = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        attrAttrgroupRelationDao.deleteBatchRelations(entities);
    }

    /*
    * 获取当前分组没有关联的所有属性
    * 1、当前分组只能关联自己所属分类里面的属性
    * 2、当前分组只能关联别的分组没有关联引用的属性
    * */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attegroundId) {
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attegroundId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //2、当前分组只能关联别的分组没有关联引用的属性
        //2.1 先找到当前分类下的其它分组，其它分组已经绑定的就不能绑定了，当然自己绑定了的也不能绑定
        //需要先解绑
        List<AttrGroupEntity> grops = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>()
                .eq("catelog_id", catelogId)
       );
        // 然后找到这些分组关联的属性
        List<Long> groupIds = grops.stream().map((item) -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());
        //找到其它分组的关联数据，从这些关联数据中获取所有已经关联的属性
        List<AttrAttrgroupRelationEntity> relationsToFindCatelog = attrAttrgroupRelationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>()
                .in("attr_group_id", groupIds));
        //从关联数据中筛选出id,这里得到的id集合是其它组已经引用的属性id集合
        List<Long> attrIds = relationsToFindCatelog.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        //2.2从当前分类的所有属性中移除这些属性,销售类型属性也要排除，销售属性没有组
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
                .eq("catelog_id", catelogId).eq("attr_type",
                        ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if(attrIds!=null&&attrIds.size()>0)
        {
        wrapper.notIn("attr_id", attrIds);
        }
        String key= (String) params.get("key");
        if(!StringUtils.isEmpty(key))
        {
            wrapper.and((wrapper1)->{
                wrapper1.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;
    }

    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIds) {
        return this.baseMapper.selectSearchAttrs(attrIds);

    }

}